package com.huawei.hmsdemo10086.Adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huawei.hmsdemo10086.Activity.EvaluateActivity;
import com.huawei.hmsdemo10086.Activity.LoginActivity;
import com.huawei.hmsdemo10086.Activity.MainActivity;
import com.huawei.hmsdemo10086.Activity.PayActivity;
import com.huawei.hmsdemo10086.POJO.Evaluate;
import com.huawei.hmsdemo10086.POJO.Goods;
import com.huawei.hmsdemo10086.POJO.Order;
import com.huawei.hmsdemo10086.POJO.Result;
import com.huawei.hmsdemo10086.R;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderAdapter extends BaseAdapter {

    private List<Order> datas = new ArrayList<Order>();
    private SharedPreferences sharedPreferences;
    private Result<Float> point_res = null;
    private Context context;
    private LayoutInflater layoutInflater;

    public OrderAdapter(Context context, List<Order> datas) {
        this.datas = datas;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return datas.size(); //返回列表的长度
    }

    @Override
    public Order getItem(int position) {
        return datas.get(position); //通过列表的位置 获得集合中的对象
    }

    @Override
    public long getItemId(int position) { // 获得集合的Item的位置
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.layout_order_node, null);//找到布局文件
            convertView.setTag(new ViewHolder(convertView));
        }
        initViews(getItem(position), (ViewHolder) convertView.getTag());
        return convertView;

    }

    private void initViews(Order data, ViewHolder holder) {//初始化数据

        /**
         * 第一次初始话的时候通过 要请求的Url地址 为每个图片设置一个Tag标记,
         * 然后在设置图片的时候判断Tag标记如果是才把图片设置到ImageView上,
         * 这做的原因是为了防止ListView 中的图片错位...
         */
        System.out.println("111");
        sharedPreferences = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        holder.num.setText(""+data.getNum());//设置Tag

        //设置新闻标题为集合中获得的标题
        holder.title.setText(data.getGoods().getName());


        holder.price.setText(""+data.getGoods().getPrice() * data.getNum());

        RoundedCorners roundedCorners = new RoundedCorners(20);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(20, 20);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).skipMemoryCache(true);

        Glide.with(context)
                .load(data.getGoods().getPicaddress())
                .apply(options)
                .into(holder.img);


        Log.d("orderInfo", data.getGoods().getGoodsid()+"/"+data.getOrderid());


        switch (data.getStatus()){
            case 0:
                holder.order_status.setText("未支付");
                holder.delete_order.setVisibility(View.GONE);
                holder.evaluate_order.setVisibility(View.GONE);
                holder.confirm_order.setVisibility(View.GONE);
                holder.apply_back.setVisibility(View.GONE);
                holder.pay_order.setVisibility(View.VISIBLE);
                holder.cancel_order.setVisibility(View.VISIBLE);
                break;
            case 1://发货
                holder.order_status.setText("待发货");
                holder.delete_order.setVisibility(View.GONE);
                holder.evaluate_order.setVisibility(View.GONE);
                holder.confirm_order.setVisibility(View.GONE);
                holder.apply_back.setVisibility(View.VISIBLE);
                holder.pay_order.setVisibility(View.GONE);
                holder.cancel_order.setVisibility(View.GONE);
                break;
            case 2://确认收货
                holder.delete_order.setVisibility(View.GONE);
                holder.order_status.setText("已发货");
                holder.confirm_order.setVisibility(View.VISIBLE);
                holder.evaluate_order.setVisibility(View.GONE);
                holder.pay_order.setVisibility(View.GONE);
                holder.cancel_order.setVisibility(View.GONE);
                holder.apply_back.setVisibility(View.VISIBLE);
                break;
            case 3://确认收货
                holder.delete_order.setVisibility(View.VISIBLE);
                holder.order_status.setText("已收货");
                holder.confirm_order.setVisibility(View.GONE);
                holder.evaluate_order.setVisibility(View.VISIBLE);
                holder.pay_order.setVisibility(View.GONE);
                holder.cancel_order.setVisibility(View.GONE);
                holder.apply_back.setVisibility(View.VISIBLE);
                break;
            case 4:
                holder.delete_order.setVisibility(View.VISIBLE);
                holder.order_status.setText("退单被拒");
                holder.confirm_order.setVisibility(View.GONE);
                holder.evaluate_order.setVisibility(View.VISIBLE);
                holder.pay_order.setVisibility(View.GONE);
                holder.cancel_order.setVisibility(View.GONE);
                holder.apply_back.setVisibility(View.VISIBLE);
                break;
            case -1:
                holder.delete_order.setVisibility(View.GONE);
                holder.order_status.setText("申请退单");
                holder.confirm_order.setVisibility(View.GONE);
                holder.evaluate_order.setVisibility(View.GONE);
                holder.pay_order.setVisibility(View.GONE);
                holder.cancel_order.setVisibility(View.GONE);
                holder.apply_back.setVisibility(View.GONE);
                break;
            case -2:
                holder.delete_order.setVisibility(View.VISIBLE);
                holder.order_status.setText("退单审核通过");
                holder.confirm_order.setVisibility(View.GONE);
                holder.evaluate_order.setVisibility(View.GONE);
                holder.pay_order.setVisibility(View.GONE);
                holder.cancel_order.setVisibility(View.GONE);
                holder.apply_back.setVisibility(View.GONE);
                break;
        }


        holder.pay_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sharedPreferences.getFloat("point",0) < data.getGoods().getPrice() * data.getNum()){
                    Toast.makeText(context, "没钱", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    String url = "http://10.0.2.2:8443/api/changeStatus";
                    OkHttpClient mOkHttpClient = new OkHttpClient();

                    String json = "{\n" +
                            "  \"status\": \"" + 1 + "\",\n" +
                            "  \"orderid\": \"" + data.getOrderid() + "\",\n" +
                            "  \"goodsid\": \"" + data.getGoods().getGoodsid()+ "\"\n" +
                            "}";

                    Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                    mOkHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("测试", e+"");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

                        }
                    });


                    url = "http://10.0.2.2:8443/api/payBill";
                    mOkHttpClient = new OkHttpClient();

                    json = "{\n" +
                            "  \"totle_price\": \"" + data.getGoods().getPrice() * data.getNum()+ "\",\n" +
                            "  \"userid\": \"" + sharedPreferences.getString("userId",null) + "\"\n" +
                            "}";

                    request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                    mOkHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("测试", e+"");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Gson gson = new Gson();
                            String rep = response.body().string();

                            Type type = new TypeToken<Result<Float>>(){}.getType();
                            point_res = gson.fromJson(rep,type);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putFloat("point",(float) point_res.getData());
                            editor.commit();

                        }
                    });
                    data.setStatus(1);
                    holder.order_status.setText("待发货");
                    holder.delete_order.setVisibility(View.GONE);
                    holder.evaluate_order.setVisibility(View.GONE);
                    holder.confirm_order.setVisibility(View.GONE);
                    holder.apply_back.setVisibility(View.VISIBLE);
                    holder.pay_order.setVisibility(View.GONE);
                    holder.cancel_order.setVisibility(View.GONE);
                }


            }
        });

        holder.cancel_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://10.0.2.2:8443/api/deleteOrder";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"goodsid\": \"" + data.getGoodsid() + "\",\n" +
                        "  \"num\": \"" + data.getNum() + "\",\n" +
                        "  \"status\": \"" + 1 + "\",\n" +
                        "  \"orderid\": \"" + data.getOrderid() + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                    }
                });
                datas.remove(data);
                notifyDataSetChanged();


            }
        });

        holder.evaluate_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, EvaluateActivity.class);
                intent.putExtra("goodsid",data.getGoodsid());
                intent.putExtra("goods_name",data.getGoods().getName());
                intent.putExtra("orderid",data.getOrderid());
                intent.putExtra("good_img_src",data.getGoods().getPicaddress());
                context.startActivity(intent);
            }
        });

        holder.delete_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://10.0.2.2:8443/api/deleteOrder";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"goodsid\": \"" + data.getGoodsid() + "\",\n" +
                        "  \"num\": \"" + data.getNum() + "\",\n" +
                        "  \"status\": \"" + -1 + "\",\n" +
                        "  \"orderid\": \"" + data.getOrderid() + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                    }
                });
                datas.remove(data);
                notifyDataSetChanged();
            }
        });

        holder.confirm_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://10.0.2.2:8443/api/changeStatus";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"goodsid\": \"" + data.getGoodsid() + "\",\n" +
                        "  \"status\": \"" + 3 + "\",\n" +
                        "  \"orderid\": \"" + data.getOrderid() + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        holder.order_status.setText("已收货");

                    }
                });
                data.setStatus(2);
                holder.delete_order.setVisibility(View.VISIBLE);
                holder.order_status.setText("已收货");
                holder.confirm_order.setVisibility(View.GONE);
                holder.evaluate_order.setVisibility(View.VISIBLE);
                holder.pay_order.setVisibility(View.GONE);
                holder.cancel_order.setVisibility(View.GONE);


            }
        });

        if(holder!=null && holder.evaluate_order.getVisibility() == View.VISIBLE && data!=null && datas.contains(data))
        {
            String url = "http://10.0.2.2:8443/api/searchEvaluate";
            OkHttpClient mOkHttpClient = new OkHttpClient();

            String json = "{\n" +
                    "  \"goodsid\": \"" + data.getGoodsid()+ "\",\n" +
                    "  \"orderid\": \"" + data.getOrderid()+ "\",\n" +
                    "  \"userid\": \"" + data.getUserid() + "\"\n" +
                    "}";

            Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("测试", e+"");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Gson gson = new Gson();
                    String rep = response.body().string();
                    System.out.println(rep);

                    Type type = new TypeToken<Result<Goods>>(){}.getType();
                    Result<Goods> result = gson.fromJson(rep,type);

                    if(result.getData() != null)
                    {
                        holder.evaluate_order.setVisibility(View.GONE);
                    }

                }
            });
        }


        holder.apply_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final EditText inputServer = new EditText(context);
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("退单理由").setView(inputServer);

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.setPositiveButton("申请", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {


                        String url = "http://10.0.2.2:8443/api/changeStatus";
                        OkHttpClient mOkHttpClient = new OkHttpClient();

                        String json = "{\n" +
                                "  \"status\": \"" + -1 + "\",\n" +
                                "  \"reason\": \"" + inputServer.getText().toString() + "\",\n" +
                                "  \"orderid\": \"" + data.getOrderid() + "\",\n" +
                                "  \"goodsid\": \"" + data.getGoods().getGoodsid()+ "\"\n" +
                                "}";

                        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                        mOkHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Log.e("测试", e+"");
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                data.setStatus(-1);

                            }
                        });

                    }
                });
                builder.show();

            }
        });



    }





    protected class ViewHolder {
        private TextView price;
        private TextView title;
        private TextView num;
        private ImageView img;
        private Button delete_order;
        private Button confirm_order;
        private Button apply_back;
        private TextView order_status;
        private Button evaluate_order;
        private Button cancel_order;
        private Button pay_order;

        public ViewHolder(View view) {
            title = (TextView) view.findViewById(R.id.goods_title);
            num = (TextView) view.findViewById(R.id.goods_num);
            price = (TextView) view.findViewById(R.id.goods_price);
            img = view.findViewById(R.id.order_item_img);
            delete_order = (Button)view.findViewById(R.id.delete_order);
            confirm_order = (Button)view.findViewById(R.id.confirm_order);
            apply_back = (Button)view.findViewById(R.id.apply_back);
            order_status = (TextView)view.findViewById(R.id.order_status);
            evaluate_order = (Button)view.findViewById(R.id.evaluate_order);
            cancel_order = (Button)view.findViewById(R.id.cancel_order);
            pay_order = (Button) view.findViewById(R.id.pay_order);
        }
    }

//    public void getImage(Context context, String imgUrl,
//                         final ImageView imageView) {
//
//        /**
//         * 检测图片的Tag值 ,如果根请求的地址相同 才做图片的网络请求.
//         */
//        if (imageView.getTag().toString().equals(imgUrl)) {
//            RequestQueue mQueue = Volley.newRequestQueue(context);
//            ImageRequest imageRequest = new ImageRequest(imgUrl,
//                    new Response.Listener<Bitmap>() {
//                        @Override
//                        public void onResponse(Bitmap response) {
//                            Bitmap outBitmap = RoundRectImageView.getRoundBitmapByShader(response, 500,300,10, 0);
//                            imageView.setImageBitmap(outBitmap);//将返回的Bitmap显示子啊ImageView上
//                        }
//                    }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
//                @Override
//                public void onErrorResponse(VolleyError error) {
//                }
//            });
//            mQueue.add(imageRequest);
//        }
//    }
}
